<?php

namespace app\index\controller;

use think\Config;
use think\Db;

class Index
{
    protected $token;
    protected $usertoken;
    protected $server_upload_path;
    protected $remote_host;

    public function __construct()
    {
        $this->server_upload_path = Config::get("server_upload_path");
        $this->remote_host = Config::get("remote_host");
        $token = input("token");
        if (!$token) {
            $token = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
        }
        $this->usertoken = $token;
        if(!$token){
            returnRst([],'请先登录!',5001);
        }
        $this->checkAuth($token);
        $this->init();
    }

    public function test()
    {
        p(123);
    }

    public function checkAuth($token)
    {
        $where['token'] = $token;
        $result = Db::name("user")->where($where)->find();
        if (!$result) {
            returnRst([], '登录已失效!', 5001);
        }
        $logintime = $result['logintime'];
    }

    public function uploadFile()
    {
        $token = input("token");
        if (!$token || $token == 'undefined') {
            returnRst([], '上传失败请先登录', 5001);
        }
        $uid = getUser($token, 'id');
        $count   = Db::name("file")->where("uid",$uid)->count();
//        if($count>5){
//            returnRst([], '上传失败!每人最多可上传5条语音进行转写!', 201);
//        }
        $file = request()->file('file');
        if ($file) {
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
            if ($info) {
                // 成功上传后 获取上传信息
                // 输出 jpg


//                echo $info->getExtension();
//                // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
//                echo $info->getSaveName();
//                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                $return['file_identifier'] = explode(".", $info->getFilename())[0];
                $return['show_name'] = $info->getInfo()['name'];
                $return['file_url'] = $this->remote_host . $info->getSaveName();
                $return['uid'] = $uid;
                $return['create_time'] = time();
                $return['file_path'] = $info->getSaveName();
                $return['play_seconds'] = get_file_size($this->server_upload_path . $info->getSaveName())?:0;
                $return['extension'] = $info->getExtension();
                $return['file_id'] = '';
                $return['fid'] = Db::name("file")->insertGetId($return);
                returnRst($return);
            } else {
                // 上传失败获取错误信息
                returnRst([], '上传失败', 201);
            }
        }
    }

    public function index()
    {
        p($this->token);

    }


    public function tests()
    {
        echo get_file_size("/www/wwwroot/rec_api/public/vod/005.wav");
    }

    public function detail()
    {
        $id = input("id");
        $result = Db::name("file")->where("id", $id)->select();
        $totalLength = 0;
        foreach ($result as $key => $row) {
            $totalLength += $row['play_seconds'];
        }
        $returnRst['data'] = $result;
        $returnRst['total'] = changeS($totalLength);
        returnRst($returnRst);
    }

    public function deleteFile()
    {
        $ids = input("ids");
        $result =  json_decode($ids,true);
        $token = $this->usertoken;
        $uid = getUser($token, 'id');
        if(!$uid){
            returnRst([], '删除失败,请重新登录!', 201);
        }
        $where['id'] = ['in',join(",",$result)];
        Db::name("file")->where($where)->delete();
        returnRst();
    }

    public function myVoice()
    {

        $token = $this->usertoken;

        $uid = getUser($token, 'id');

        $page = input("page");
        $pagesize = input("pagesize");
        $content =  input("content");
        $limit = ($page-1) * $pagesize .",".$pagesize;
        $where['uid'] = $uid;
        $where['file_id'] = ['gt',0];
        $where['show_name'] = ['like',"%$content%"];
        $result = Db::name("file")->where($where)->limit($limit)->order("create_time desc")->select();
        $total =  Db::name("file")->where($where)->count();
        foreach ($result as $key => &$row) {

            $detail = $this->fileDetail($row['file_id']);


            if(!$row['play_seconds']) {
                if (isset($detail['data']['audio_time'])) {
                    $audio_time = $detail['data']['audio_time'];
                    $row['play_seconds']    = $this->changeSecond($audio_time, $row['id']);
                }
            }

            if(isset($detail['data']['lvsr_data'])) {
                $detail['data']['current_progress'] = floatval($detail['data']['current_progress']);
                $detail['data']['total_progress'] = floatval($detail['data']['total_progress']);
                if($detail['data']['current_progress']>0 && $detail['data']['total_progress']>9) {
                    $calc_result = $detail['data']['current_progress'] / $detail['data']['total_progress'];
                }else{
                    $calc_result = 0;
                }
                if($calc_result>0){
                    $row['process'] = sprintf("%.2f",($calc_result)) * 100 ."%";
                }else{
                    $row['process'] = '0%';
                }
                $row['word_len'] = $this->getWord($detail['data']['lvsr_data']);

                $row['audio'] = $detail['data']['audio'];

                $row['lvsr_data'] = $detail['data']['lvsr_data'];

                if($detail['data']['lvsr_status'] !="非实时完成") {
                    $row['lvsr_status'] = $detail['data']['lvsr_status'].",当前进度".$row['process'];
                }else{
                    $row['lvsr_status'] = $detail['data']['lvsr_status'];
                }



                $row['scene'] = $detail['data']['scene'];
            }
            $row['create_time'] = date("Y-m-d H:i:s", $row['create_time']);


            $row['filesize'] = round(filesize($this->server_upload_path. $row['file_path']) / 1024 / 1024, 2) . "M";
            $row['play_seconds'] = changeS($row['play_seconds']);
        }
        $return['data'] = $result;
        $return['total'] = $total;
        returnRst($return);
    }

    public function getWord($data)
    {
        $word_length = 0;
        $word = '';
        if (count($data) > 0) {
            foreach ($data as $row) {
                $word .= $row['txt'];
            }
        }
        $word_length = strlen($word);
        return $word_length;
    }

    public function submits()
    {
        $id = input("id");
        $result = Db::name("file")->where("id", $id)->find();

        $extension = $result['extension'];

        $rst = $this->burstUpload($result['file_identifier'], $result['show_name'], $result['file_path'],$extension);
        $file_id = $this->audioUpload($result['file_identifier'], $result['show_name'],$extension);
        $update['file_id'] = $file_id;
        $update['is_up'] = 1;
        Db::name("file")->where("id", $id)->update($update);

        $init = $this->initTrigger($file_id);


        returnRst();

    }

    public function burstUpload($identifier, $file_name, $file_path,$extension)
    {
        $burstUpload_url = Config::get("burstUpload");


        $uploadData['chunkNumber'] = 1;
        $uploadData['totalChunks'] = 1;
        $uploadData['identifier'] = $identifier;
        $uploadData['filename'] = $file_name;
        $uploadData['file'] = curl_file_create($this->server_upload_path.$file_path, $extension, $file_name);

        $uploadData['token'] = $this->token;
        return fileUpload($burstUpload_url, $uploadData);

    }

    public function audioUpload($identifier, $filename,$extension)
    {
        $audioUpload = Config::get("audioUpload");
        $audioUploadData['token'] = $this->token;
        $audioUploadData['identifier'] = $identifier;
        $audioUploadData['filename'] = $filename;
        $audioUploadData['formatName'] = $identifier . ".".$extension;
        $audioUploadData['id'] = 5;
        $result = curl_post($audioUpload, $audioUploadData);

        $data = json_decode($result, true);
        return $data['data']['fileId'];

    }

    public function initTrigger($id)
    {
        $initTrigger_url = Config::get("initTrigger");

        $initData['token'] = $this->token;
        $initData['id'] = $id;

        $result = curl_post($initTrigger_url, $initData);
        return $result;
    }


    public function fileDetail($id = '')
    {
        $fileDetail_url = Config::get("fileDetail");

        $initData['token'] = $this->token;
        $initData['id'] = $id;
//        p(json_decode(curl_post($fileDetail_url,$initData),true));

        return json_decode(curl_post($fileDetail_url, $initData), true);

    }
    public function httpDetail()
    {
        $id = input("id");
        $uid = getUser($this->usertoken,'id');
        $where['id']  = $id;
        $where['uid'] = $uid;
        $file_info  = Db::name("file")->where("id",$id)->find();

        if(!$file_info){
            returnRst([],'系统异常!',201);
        }
        $fileDetail_url = Config::get("fileDetail");

        $initData['token'] = $this->token;
        $initData['id'] = $file_info['file_id'];
//        p(json_decode(curl_post($fileDetail_url,$initData),true));



        $result =  json_decode(curl_post($fileDetail_url, $initData), true);
        if(isset($result['data']['audio_time'])){
            $audio_time = $result['data']['audio_time'];
            $this->changeSecond($audio_time,$id);
        }
        if(!$file_info['lvsr_data'])
        {
            $update['lvsr_data'] =  $file_info['lvsr_data'] =  json_encode($result['data']['lvsr_data']);

            Db::name("file")->where("id",$id)->update($update);
        }
        $returnRst['other_info'] = $this->getFileInfo($file_info,$result['data']['lvsr_status']);
        $lvsr_data =  json_decode($file_info['lvsr_data'],true);
        $returnRst['url'] = $result['data']['audio'];
        $returnRst['data'] = $lvsr_data;
        returnRst($returnRst);
    }

    public function getFileInfo($file_data,$status)
    {
        $return['filesize'] = round(filesize($this->server_upload_path . $file_data['file_path']) / 1024 / 1024, 2) . "M";
        $return['play_seconds'] =changeS($file_data['play_seconds']);
        $return['create_time'] = date("Y-m-d H:i:s",$file_data['create_time']);
        $return['lingyu'] = '通用场景';
        $return['status'] = $status;
        return $return;
    }

    public function httpDetailSave(){
        $result = input("");
        $id = $result['id'];
        $content = $result['content'];
        $uid = getUser($this->usertoken,'id');
        $where['id']  = $id;
        $where['uid'] = $uid;
        $file_info  = Db::name("file")->where("id",$id)->find();

        if(!$file_info){
            returnRst([],'系统异常!',201);
        }


        $update['lvsr_data'] = json_encode($content);

        Db::name("file")->where("id",$id)->update($update);

        returnRst();

    }

    public function changeSecond($audio_time,$id)
    {
        $audio_time_data = explode(":",$audio_time);
        $seconds = $audio_time_data[0] * 3600 + $audio_time_data[1]*60 + $audio_time_data[2];
        Db::name("file")->where("id",$id)->update(['play_seconds'=>$seconds]);
        return $seconds;
    }

    public function t()
    {
        $res = input("");


        p($res);
    }


    /**
     * 登录接口
     * 获取全局token
     */
    public function init()
    {
        $data['account'] = 'test01';
        $data['password'] = '123456';
        $data['no_validate'] = 1;
        $result = curl_post(Config::get("loginUrl"), $data);

        $returnRst = json_decode($result, true);
        $this->token = $returnRst['data']['token'];
    }



    public function fileSpeech()
    {
        $url  = Config::get("base_url")."speechData";

        $id=  input("id");
        $file_info = Db::name("file")->where("id",$id)->find();


        $file_id = $file_info['file_id'];

        $mood_type = input("mood_type",0);
        $is_initial = input("is_initial",0);
        $sensitive_type = input("sensitive_type",0);






        $data['token'] = $this->token;
        $data['id'] = $file_id;
        $data['mood_type'] = $mood_type; //语气词过滤
        $data['is_initial'] = $is_initial;//显示原始文档
        $data['sensitive_type'] = $sensitive_type;//敏感词替换

        $result = curl_post($url,$data);
        $returnRst = json_decode($result,true);
        returnRst($returnRst['data']['lvsr_data']);
    }


    public function rolechange($file_id)
    {
        $url  = Config::get("base_url")."/transfer/separate/start";



        $data['token'] = $this->token;
        $data['fid'] = $file_id;
        $data['port'] = 0;//0 pc 1 安卓 2ios
        $data['num'] = 2;
        curl_post($url,$data);

        $detail_url = Config::get("base_url") . "transfer/separate/get";
        $detail_data['token'] = $this->token;
        $detail_data['fid'] = $file_id;
        $detail_data['num'] = 2;
        $detail_rst  =  curl_post($detail_url, $data);

    }


    public function rolechangeStatus($file_id)
    {
        $url  = Config::get("base_url")."transfer/role/status/get";
//        $id=  input("id");

//        $file_info = Db::name("file")->where("id",$id)->find();
//        $file_id = $file_info['file_id'];


        $data['token'] = $this->token;
        $data['fid'] = $file_id;
        $data['port'] = 0;//0 pc 1 安卓 2ios
        $data['status'] = -1;
        $result = curl_post($url,$data);

        $returnRst = json_decode($result,true);


        if(isset($returnRst['data']['list'][0]['status']))
        {
            if($returnRst['data']['list'][0]['status']==0) {
            }
            return $returnRst['data']['list'][0]['status'];
        }else{
            return '-1';
        }


    }



    public function roleDetail()
    {
        $url  = Config::get("base_url")."transfer/separate/get";
        $id=  input("id");

        $file_info = Db::name("file")->where("id",$id)->find();
        $file_id = $file_info['file_id'];


        $status  =  $this->rolechangeStatus($file_id);
        if($status==1) {
            if ($file_info['separate']) {
                $detail = json_decode($file_info['separate'],true);
                returnRst($detail);
            } else {
                $data['token'] = $this->token;
                $data['fid'] = $file_id;
                $data['num'] = 2;
                $result = curl_post($url, $data);
                $returnRst = json_decode($result, true);
                if(isset($returnRst['data']['separate'])) {
                    $detail = $returnRst['data']['separate'];

                    $update['separate'] = json_encode($detail);

                    Db::name("file")->where("id", $id)->update($update);

                    returnRst($detail);
                }else{
                    returnRst();
                }
            }
        }else{

            if($status==-1) {
                $this->rolechange($file_id);
            }




            returnRst(['file_id'=>$file_id],'角色分离进行中..',201);
        }

    }


    public function downLoadTxt()
    {
        $file_id = input("file_id");
        $file_info = Db::name("file")->where("id",$file_id)->find();


        $file_id = $file_info['file_id'];
        $lvsr_data = json_decode($file_info['lvsr_data'],true);
        $txt =  array_column($lvsr_data,"txt");
        $txt_str = join("\n",$txt);

        $downloadPostUrl = Config::get("downloadTxt");
        $baseUrl = Config::get("base_url");
        $data['id'] = $file_id;
        $data['token'] = $this->token;
        $data['new'] = 1;
        $data['data'] = $txt_str;

        $result = curl_post($downloadPostUrl,$data);

        $returnRst = json_decode($result,true);

        $url = '';

        if(isset($returnRst['data']['path'])){
            $url =  str_replace("/disc1/data/wwwroot/api.raisound.com/html/huisheng_api/",$baseUrl,$returnRst['data']['path']);
        }

        $return['url'] = $url;

        returnRst($return);


    }

}
